/**
 * 高级缓存管理器
 * 支持内存缓存、localStorage持久化、缓存失效策略等
 */

interface CacheItem<T> {
  data: T;
  timestamp: number;
  expiry: number;
  version: string;
}

interface CacheConfig {
  defaultTTL: number; // 默认缓存时间 (毫秒)
  maxMemoryItems: number; // 内存缓存最大条目数
  enablePersistence: boolean; // 是否启用持久化
  version: string; // 缓存版本，用于缓存失效
}

class CacheManager {
  private memoryCache = new Map<string, CacheItem<any>>();
  private config: CacheConfig;
  private readonly STORAGE_PREFIX = 'drama_cache_';

  constructor(config: Partial<CacheConfig> = {}) {
    this.config = {
      defaultTTL: 5 * 60 * 1000, // 5分钟
      maxMemoryItems: 100,
      enablePersistence: true,
      version: '1.0.0',
      ...config
    };
  }

  /**
   * 设置缓存
   */
  set<T>(key: string, data: T, ttl?: number): void {
    const expiry = Date.now() + (ttl || this.config.defaultTTL);
    const cacheItem: CacheItem<T> = {
      data,
      timestamp: Date.now(),
      expiry,
      version: this.config.version
    };

    // 内存缓存
    this.memoryCache.set(key, cacheItem);
    this.enforceMemoryLimit();

    // 持久化缓存
    if (this.config.enablePersistence) {
      try {
        localStorage.setItem(
          this.STORAGE_PREFIX + key,
          JSON.stringify(cacheItem)
        );
      } catch (error) {
        console.warn('Failed to persist cache:', {
          key,
          error: (error as any)?.message || String(error),
          storageQuotaExceeded: (error as any)?.name === 'QuotaExceededError'
        });

        // 如果是存储空间不足，尝试清理一些缓存
        if ((error as any)?.name === 'QuotaExceededError') {
          this.clearOldPersistentCache();
        }
      }
    }
  }

  /**
   * 获取缓存
   */
  get<T>(key: string): T | null {
    const startTime = performance.now();

    // 先检查内存缓存
    let cacheItem = this.memoryCache.get(key);
    let fromMemory = true;

    // 如果内存中没有，尝试从localStorage获取
    if (!cacheItem && this.config.enablePersistence) {
      fromMemory = false;
      try {
        const stored = localStorage.getItem(this.STORAGE_PREFIX + key);
        if (stored) {
          cacheItem = JSON.parse(stored);
          // 恢复到内存缓存
          if (cacheItem) {
            this.memoryCache.set(key, cacheItem);
          }
        }
      } catch (error) {
        console.warn('Failed to read from localStorage:', {
          key,
          error: (error as any)?.message || String(error)
        });
        // 删除损坏的缓存项
        try {
          localStorage.removeItem(this.STORAGE_PREFIX + key);
        } catch (removeError) {
          console.warn('Failed to remove corrupted cache item:', removeError);
        }
      }
    }

    if (!cacheItem) {
      // 记录缓存未命中
      const duration = performance.now() - startTime;
      if (import.meta.env.DEV) {
        console.log(`Cache miss: ${key} (${duration.toFixed(2)}ms)`);
      }
      return null;
    }

    // 检查版本
    if (cacheItem.version !== this.config.version) {
      this.delete(key);
      return null;
    }

    // 检查是否过期
    if (Date.now() > cacheItem.expiry) {
      this.delete(key);
      return null;
    }

    // 记录缓存命中
    const duration = performance.now() - startTime;
    if (import.meta.env.DEV) {
      console.log(`Cache hit: ${key} (${fromMemory ? 'memory' : 'localStorage'}, ${duration.toFixed(2)}ms)`);
    }

    return cacheItem.data;
  }

  /**
   * 删除缓存
   */
  delete(key: string): void {
    this.memoryCache.delete(key);
    if (this.config.enablePersistence) {
      localStorage.removeItem(this.STORAGE_PREFIX + key);
    }
  }

  /**
   * 清空所有缓存
   */
  clear(): void {
    this.memoryCache.clear();
    if (this.config.enablePersistence) {
      const keys = Object.keys(localStorage);
      keys.forEach(key => {
        if (key.startsWith(this.STORAGE_PREFIX)) {
          localStorage.removeItem(key);
        }
      });
    }
  }

  /**
   * 检查缓存是否存在且有效
   */
  has(key: string): boolean {
    return this.get(key) !== null;
  }

  /**
   * 获取缓存统计信息
   */
  getStats() {
    const memorySize = this.memoryCache.size;
    let persistentSize = 0;
    
    if (this.config.enablePersistence) {
      const keys = Object.keys(localStorage);
      persistentSize = keys.filter(key => 
        key.startsWith(this.STORAGE_PREFIX)
      ).length;
    }

    return {
      memorySize,
      persistentSize,
      maxMemoryItems: this.config.maxMemoryItems
    };
  }

  /**
   * 强制执行内存限制
   */
  private enforceMemoryLimit(): void {
    if (this.memoryCache.size <= this.config.maxMemoryItems) return;

    // 按时间戳排序，删除最旧的条目
    const entries = Array.from(this.memoryCache.entries());
    entries.sort((a, b) => a[1].timestamp - b[1].timestamp);

    const toDelete = entries.slice(0, entries.length - this.config.maxMemoryItems);
    toDelete.forEach(([key]) => {
      this.memoryCache.delete(key);
    });
  }

  /**
   * 清理旧的持久化缓存（当存储空间不足时）
   */
  private clearOldPersistentCache(): void {
    try {
      const keys = Object.keys(localStorage);
      const cacheKeys = keys.filter(key => key.startsWith(this.STORAGE_PREFIX));

      // 获取缓存项的时间戳并排序
      const cacheItems = cacheKeys.map(key => {
        try {
          const item = JSON.parse(localStorage.getItem(key) || '{}');
          return { key, timestamp: item.timestamp || 0 };
        } catch {
          return { key, timestamp: 0 };
        }
      }).sort((a, b) => a.timestamp - b.timestamp);

      // 删除最旧的一半缓存项
      const toDelete = cacheItems.slice(0, Math.floor(cacheItems.length / 2));
      toDelete.forEach(({ key }) => {
        try {
          localStorage.removeItem(key);
        } catch (error) {
          console.warn('Failed to remove cache item:', key, error);
        }
      });

      console.log(`Cleared ${toDelete.length} old cache items to free up storage space`);
    } catch (error) {
      console.error('Failed to clear old persistent cache:', error);
    }
  }

  /**
   * 清理过期缓存
   */
  cleanup(): void {
    const now = Date.now();
    
    // 清理内存缓存
    for (const [key, item] of this.memoryCache.entries()) {
      if (now > item.expiry) {
        this.memoryCache.delete(key);
      }
    }

    // 清理持久化缓存
    if (this.config.enablePersistence) {
      const keys = Object.keys(localStorage);
      keys.forEach(key => {
        if (key.startsWith(this.STORAGE_PREFIX)) {
          try {
            const stored = localStorage.getItem(key);
            if (stored) {
              const item = JSON.parse(stored);
              if (now > item.expiry || item.version !== this.config.version) {
                localStorage.removeItem(key);
              }
            }
          } catch (error) {
            // 删除损坏的缓存项
            localStorage.removeItem(key);
          }
        }
      });
    }
  }
}

// 创建全局缓存实例
export const cacheManager = new CacheManager({
  defaultTTL: 5 * 60 * 1000, // 5分钟
  maxMemoryItems: 50,
  enablePersistence: true,
  version: '1.0.0'
});

// 定期清理过期缓存
setInterval(() => {
  cacheManager.cleanup();
}, 60 * 1000); // 每分钟清理一次

// 在开发环境下暴露到全局对象，方便调试
if (import.meta.env.DEV) {
  (window as any).cacheManager = cacheManager;
}

export default CacheManager;
